<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\User\PartnerModel;
use app\api\model\User\UserApplyPartnerModel;
use app\api\model\User\UserVipCodeModel;
use app\api\validate\PartnerValidate;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;

class Partner extends AppController
{

    /**
     * @api {get} /get_partner_info 合伙人详情
     * @apiGroup 合伙人
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     * {
     *   "id":"类型ID",
     *   "partner_name":"合伙人名称",
     *   "img":"图片",
     *   "slider_img":"图片数组",
     *   "details":"详情",
     *   "price":"普通价",
     *   "vip_price":"VIP价",
     *   "cost_price":"成本价",
     *   "code_list":"邀请码列表",
     *   "is_partner":"是否成为合伙人 0：否 1：是",
     * }
     * @apiVersion 1.0.0
     */
    public function getPartnerInfo(Request $request)
    {
        $user = $this->user;
        $partner = PartnerModel::getPartnerWhere([['id','=',1]]);
        if(!empty($partner)){
            $partner['img'] = ImageUtil::i()->replaceUrl($partner['img']);
            $images = !empty($partner['slider_img']) ? json_decode($partner['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $partner['slider_img'] = $images;
            $partner['details'] = !empty($partner['details']) ? htmlspecialchars_decode($partner['details']) : "";
        }
        if(!empty($user)){
            $list = UserVipCodeModel::getUserVipCodeWhereMore([['uid','=',$user['id']]],"id,code,uid,status");
            $partner['code_list'] = $list;
            $partner['is_partner'] = $user['is_partner'];
        }else{
            $partner['code_list'] = [];
            $partner['is_partner'] = 0;
        }
        return Util::returnJson(self::CODE_SUCCESS,$partner);
    }

    /**
     * @api {post} /get_partner_info 预创建购买合伙人
     * @apiGroup 合伙人
     * @apiParam {string} token Token
     * @apiParam {int} partner_id 合伙人ID
     * @apiParam {string} real_name 姓名
     * @apiParam {string} mobile 手机号
     * @apiParam {string} region 地区信息
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     * {
     *   "partner_id":"合伙人ID",
     *   "real_name":"姓名",
     *   "mobile":"电话",
     *   "region":"地址",
     *   "total_price":"总价",
     *   "pay_price":"支付价格",
     *   "deduction_price":"优惠",
     *   "partner":"合伙人信息"
     * }
     * @apiVersion 1.0.0
     */
    public function perOrderPartnerInfo(Request $request)
    {
        $param = $request->param();
        $user = $this->user;

        try {
            validate(PartnerValidate::class)->scene('info')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR,null,$e->getError());
        }

        $partner = PartnerModel::getPartnerWhere([['id','=',$param['partner_id']]]);
        if(!empty($partner)){
            $partner['img'] = ImageUtil::i()->replaceUrl($partner['img']);
            $images = !empty($partner['slider_img']) ? json_decode($partner['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $partner['slider_img'] = $images;
            $partner['details'] = !empty($partner['details']) ? htmlspecialchars_decode($partner['details']) : "";
        }
        $total_price = 0;
        $pay_price = 0;
        $deduction_price = 0;
        if(!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time() )){
            //VIP
            $total_price = $partner['vip_price'];
            $pay_price = $total_price;
        }else{
            $total_price = $partner['price'];
            $pay_price = $total_price;
        }
        $data = [
            'partner_id' => !empty($param['partner_id']) ? $param['partner_id'] : 0,
            'real_name' => !empty($param['real_name']) ? $param['real_name'] : "",
            'mobile' => !empty($param['mobile']) ? $param['mobile'] : "",
            'region' => !empty($param['region']) ? $param['region'] : "",
            'total_price' => $total_price,
            'pay_price' => $pay_price,
            'deduction_price' => $deduction_price,
            'partner' => $partner
        ];
        return Util::returnJson(self::CODE_SUCCESS,$data);
    }

    /**
     * @api {post} /create_order_partner 购买合伙人下单支付
     * @apiGroup 合伙人
     * @apiParam {string} token Token
     * @apiParam {int} partner_id 合伙人ID
     * @apiParam {string} real_name 姓名
     * @apiParam {string} mobile 手机号
     * @apiParam {string} region 地区信息
     * @apiParam {int} source_type 来源 1:APP 2:微信公众号 3:小程序
     * @apiParam {int} pay_way 支付方式 1:余额 2:支付宝 3:微信
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function createOrderPartner(Request $request)
    {
        $param = $request->param();
        $user = $this->user;

        if(!empty($user['is_partner'])){
            return Util::returnJson(self::CODE_ERROR,null,"你已经是合伙人了无需购买");
        }

        try {
            validate(PartnerValidate::class)->scene('info')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR,null,$e->getError());
        }

        //1:APP 2:微信公众号 3:小程序
        if (!in_array($param['source_type'],[1,2,3])) {
            return Util::returnJson(self::CODE_ERROR,null,"来源错误");
        }
        if (!in_array($param['pay_way'],[1,2,3])) {
            return Util::returnJson(self::CODE_ERROR,null,"支付类型错误");
        }

        $partner = PartnerModel::getPartnerWhere([['id','=',$param['partner_id']]]);
        if(!empty($partner)){
            $partner['img'] = ImageUtil::i()->replaceUrl($partner['img']);
            $images = !empty($partner['slider_img']) ? json_decode($partner['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $partner['slider_img'] = $images;
            $partner['details'] = !empty($partner['details']) ? htmlspecialchars_decode($partner['details']) : "";
        }
        $total_price = 0;
        $pay_price = 0;
        $deduction_price = 0;
        if(!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time() )){
            //VIP
            $total_price = $partner['vip_price'];
            $pay_price = $total_price;
        }else{
            $total_price = $partner['price'];
            $pay_price = $total_price;
        }

        //商户订单号
        $out_trade_no = StrUtil::i()->getOrderSn(3);
        //合伙人订单号
        $order_sn = StrUtil::i()->getOrderSn();

        $data = [
            'order_sn'        => $order_sn,
            'uid'             => $user['id'],
            'partner_id'      => !empty($param['partner_id']) ? $param['partner_id'] : 0,
            'real_name'       => !empty($param['real_name']) ? $param['real_name'] : "",
            'mobile'          => !empty($param['mobile']) ? $param['mobile'] : "",
            'region'          => !empty($param['region']) ? $param['region'] : "",
            'total_price'     => $total_price,
            'pay_price'       => $pay_price,
            'deduction_price' => $deduction_price,
            'partner_info'    => json_encode($partner),
            'status'          => 0,
            'pay_way'         => $param['pay_way'],
            'source_type'     => $param['source_type'],
            'up_time'         => date('Y-m-d H:i:s',time()),
            'add_time'        => date('Y-m-d H:i:s',time())
        ];
        Db::startTrans();
        try {
            $id = UserApplyPartnerModel::addUserApplyPartner($data);
            if($id){
                //支付信息
                //支付
                if($param['pay_way'] == 1){
                    //余额支付
                }else if($param['pay_way'] == 2){
                    $partner_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    UserApplyPartnerModel::updateUserApplyPartnerWhere([['id','=',$id]],$partner_save);
                    //支付宝支付
                    $result = $this->aliPay($data['total_price'],$out_trade_no,"购买合伙人",1);
                }else if($param['pay_way'] == 3){
                    //微信支付
                    $partner_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    UserApplyPartnerModel::updateUserApplyPartnerWhere([['id','=',$id]],$partner_save);
                    $result = $this->weChatPay("APP",$data['total_price'],$out_trade_no,"购买合伙人",1);
                }

                if ($result['code'] == 0) {
                    $data = [
                        'pay_way'  => $param['pay_way'],
                        'pay_info' => $result['data']
                    ];
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS,$data,"下单成功");
                }else{
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR,null,$result['msg']);
                }
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"创建订单失败");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"创建订单失败");
        }
    }

}